<template>
  <div class="enroll-container">
    <div class="enroll-content">
      <h3>注册页面</h3>
      <el-form :model="enrollForm" :rules="enrollRules" ref="enrollFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="enrollForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="enrollForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="enrollForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleEnroll">注册</el-button>
          <el-button @click="handleGoToLogin">返回登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 定义注册表单数据
const enrollForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
});

// 定义注册表单验证规则
const enrollRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== enrollForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 定义注册表单引用
const enrollFormRef = ref(null);
enrollFormRef.value = undefined;

// 处理注册逻辑
const handleEnroll = async () => {
  await enrollFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.post('http://localhost:8080/api/users/register', {
          username: enrollForm.value.username,
          password: enrollForm.value.password
        });
        console.log(response)
        // const { success, message } = response;
        const success = response.status.valueOf(200)
        const message = response.data
        if (success) {
          alert('注册成功，请登录');
          console.log("success")
          await router.push('/login');
        } else {
          alert(message);
        }
      } catch (error) {
        console.error('注册请求出错:', error.response.data);
        alert('注册请求出错' + error.response.data);
      }
    } else {
      console.log('表单验证失败');
    }
  });
};

// 处理返回登录页面逻辑
const handleGoToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.enroll-container {
  background-color: #e0f7fa; /* 浅蓝色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.enroll-content {
  width: 350px;
  background-color: #fff;
  padding: 20px;
}
</style>